#!/usr/bin/perl

use strict;

package main;

use Getopt::Long;
use List::Util qw(first);
use Lunmgr ':all';
use Data::Dumper;

my %_cmds = (
    qlrescan => '/usr/local/bin/ql-dynamic-tgt-lun-disc.sh',
    lsscsi => '/usr/bin/lsscsi',

);

my %_opts;

GetOptions(\%_opts,
          "-help|h");

my @devices = ReadTable("/home/lunmgr/lunmgr.devtable");

LogDebug("$_cmds{qlrescan} 2>/dev/null");

# this is only a demo
my @ql_outputs = qw(0:0:0:0 1:0:7:6 1:0:7:7 1:0:7:8);
chomp (my @alldisks = `$_cmds{lsscsi}`);

foreach my $hbtl (@ql_outputs) {
    my $devline = first { /$hbtl/ } @alldisks;
    next unless $devline;

    my $lun = $hbtl;
    $lun =~ s/.*://g;

    my @fields = split /\s+/, $devline;
    my $sddev = $fields[-1];
    $sddev =~ s/.*\///;

    my $wwn = GetWwnForDev($fields[-1], 1);

    LogMsg("New device: " . $fields[-1] . "($hbtl)=$wwn:$lun");
    next unless $wwn;

    my $device = first { $_->wwn eq $wwn && $_->lun eq $lun } @devices;
    if ($device) {
        LogMsg("Updating " . $device->path . "(" . $device->uuid . ")");
        my $uuid = GetUuidForDev($sddev, 1);
        $device->set_uuid($uuid) if ($device->uuid =~ /REMOVED/);
    }
}

WriteTable(@devices);

